<?php


namespace App\Shuixing\Controllers;


use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\WxCommentLike;
use App\Models\WxUser;

class SingleController
{
    public function index($id)
    {

        $data = WxPost::where('id', $id)
            ->first();
        $data->user = WxUser::where('id', $data->user_id)
            ->first(['user_avatar', 'user_name', 'id', 'user_introduce', 'is_member', 'is_official', 'is_authentication']);//发帖人
        $tagsIds = WxPostsTag::where('posts_id', $id)->pluck('tags_id');//标签ID列表
        $data->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);//标签列表
        $data->like_count = WxLike::where('posts_id', $id)->count(); // 帖子喜欢数量
        $data->comment_count = WxComment::where(['posts_id' => $id, 'comment_state' => 1])->count(); // 评论数量
        $data->image = WxPostsImg::where('posts_id', $id)->get(); // 帖子图片
        $data->video = WxPostsVideo::where('posts_id', $id)->first(['video_thumb_url', 'video_url']);
        $data->format_time = format_datetime($data->created_at); // 发帖时间

        //评论
        $comment = WxComment::where('comment_state', 1)->where('posts_id', $id)
            ->where('comment_id', null)
            ->get();
        $comment->append(['format_time']);
        $comment->map(function ($item) {
            $imgList = array();
            array_push($imgList, ['img_url' => $item->comment_img_url]);
            $item->like_count = WxCommentLike::where('comment_id', $item->id)->count();
            $item->imgList = $imgList;
            $childData = WxComment::where('comment_id', $item->id)->get(['id', 'user_name', 'comment_content', 'user_id', 'posts_user_id', 'user_avatar', 'comment_img_url', 'created_at', 'comment_agent_name', 'comment_agent_id']);
            $childData->map(function ($item) {
                $imgList = array();
                array_push($imgList, ['img_url' => $item->comment_img_url]);
                $item->like_count = WxCommentLike::where('comment_id', $item->id)->count();
                $item->imgList = $imgList;
            });
            $childData->append(['format_time']);
            $item->child = $childData;
        });

        $link = 'https://qh-admin.supengjun.com/single/' . $id;

        return view('shuixing/single', ['data' => $data, 'comment' => $comment, 'link' => $link]);
    }
}
